package product

import (
	"fmt"
	"vue-admin-server/global"
	"vue-admin-server/model/product"
	"vue-admin-server/model/product/response"
)

type CosReportService struct{}

func (crs *CosReportService) GetCosReportHistory(chipIdStr string) ([]product.CosReport, error) {
	var cosReports []product.CosReport
	err := global.GVA_DB.Where("chip_id = ?", chipIdStr).Order("test_time desc").Find(&cosReports).Error
	if err != nil {
		return nil, err
	}
	return cosReports, nil
}

func (crs *CosReportService) GetCosReportInfo(chipIdStr, reportIdStr string) (*response.ChipCosReport, error) {
	var chipSpec product.ChipSpec
	err := global.GVA_DB.First(&chipSpec, "id = ?", chipIdStr).Error
	if err != nil {
		return nil, err
	}

	var cosReport product.CosReport
	err = global.GVA_DB.First(&cosReport, "id = ?", reportIdStr).Error
	if err != nil {
		return nil, err
	}

	cosReportResp := &response.ChipCosReport{
		ChipID:        chipSpec.ID,
		Supplier:      chipSpec.Supplier,
		ChipNo:        chipSpec.ChipNo,
		RaycusNo:      chipSpec.RaycusNo,
		TestTime:      cosReport.TestTime,
		TestContent:   cosReport.TestContent,
		ReportFileURL: cosReport.ReportFileURL,
		Params:        make(map[string][]response.ChipCosReportParam, 0),
	}

	sqlStr := `
SELECT 
    cpv.id AS id,
    cpv.report_id AS chip_id,
    cp.item_id AS item_id,
    cp.item AS item,
    cp.parameter_id AS parameter_id,
    cp.parameter AS parameter,
    cp.symbol AS symbol,
    cp.unit AS unit,
    cpv.test_condition AS test_condition,
    cpv.min_value AS min_value,
    cpv.max_value AS max_value,
    cpv.typical_value AS typical_value
FROM
    chip_parameter_values cpv
        LEFT JOIN
    chip_parameters cp ON cpv.item_id = cp.item_id
        AND cpv.parameter_id = cp.parameter_id
WHERE
    report_id = %v AND report_type = 'COS'
ORDER BY id

`
	params := make([]response.ChipCosReportParam, 0)
	err = global.GVA_DB.Raw(fmt.Sprintf(sqlStr, reportIdStr)).Find(&params).Error
	if err != nil {
		return cosReportResp, nil
	}

	for _, p := range params {
		if p.ItemID == "chip_surface" {
			cosReportResp.Params["chip_surface"] = append(cosReportResp.Params["chip_surface"], p)
		} else if p.ItemID == "eutectic_quality" {
			cosReportResp.Params["eutectic_quality"] = append(cosReportResp.Params["eutectic_quality"], p)
		} else if p.ItemID == "photoelectric_parameter" {
			cosReportResp.Params["photoelectric_parameter"] = append(cosReportResp.Params["photoelectric_parameter"], p)
		} else if p.ItemID == "reliability_test" {
			cosReportResp.Params["reliability_test"] = append(cosReportResp.Params["reliability_test"], p)
		}
	}
	return cosReportResp, nil
}
